package com.lucifer.treasure;

import com.lucifer.treasure.config.ConfigHandler;
import com.lucifer.treasure.registry.EnchantRegistry;
import com.lucifer.treasure.registry.EnchantEffectRegistry;
import com.lucifer.treasure.registry.LuciferTreasureTags;
import com.lucifer.treasure.enchant.effect.*;
import com.lucifer.treasure.command.SwordAuraToggleCommand;
import com.lucifer.treasure.command.SwordAuraStatusCommand;
import com.lucifer.treasure.network.SwordAuraHUDPacket;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.loader.api.FabricLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Arrays;
import java.util.List;

public class ModLuciferTreasure implements ModInitializer {

  public static final String MODID = "lucifer_treasure";
  public static final Logger LOGGER = LoggerFactory.getLogger(MODID);
  
  // 所有可用的附魔名称列表
  public static final List<String> ALL_ENCHANT_NAMES = Arrays.asList(
      "auto_smelt", "step", "steady", "experience_boost", "traveller", "magnet",
      "excavation", "reach", "venom", "beheading", "disarm", "growth",
      "life_leech", "beekeeper", "block_reach", "multibow", "quickdraw",
      "multijump", "laststand", "gloom_curse", "ender_pearl", "sword_aura"
  );

  @Override
  public void onInitialize() {
    LOGGER.info("正在初始化 路西法的宝藏 模组...");
    
    // Initialize configuration system
    ConfigHandler.init(FabricLoader.getInstance().getConfigDir());
    LOGGER.info("配置系统已初始化");
    
    // Initialize custom tags first
    LuciferTreasureTags.initialize();
    LOGGER.info("自定义标签已初始化");
    
    // Register enchantment effects first
    EnchantEffectRegistry.registerEnchantmentEffects();
    
    // Register enchantments (RegistryKey only for now)
    EnchantRegistry.registerEnchantments();
    LOGGER.info("附魔注册完成");
    
    // 🔧 注册命令处理器
    CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
        SwordAuraToggleCommand.register(dispatcher);
        SwordAuraStatusCommand.register(dispatcher);
    });
    LOGGER.info("命令处理器已注册");
    
    // 🌐 注册网络包
    SwordAuraHUDPacket.register();
    LOGGER.info("自定义网络包已注册");
    
    // Print configuration status
    printEnchantConfigStatus();
    
    // Initialize event listeners for all enchantment effects
    LOGGER.info("正在初始化附魔效果监听器...");
    
    // 只初始化启用的附魔效果
    if (EnchantRegistry.isEnchantEnabled("excavation")) {
    ExcavationEnchantmentEffect.initialize();
        LOGGER.info("连锁挖掘附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("auto_smelt")) {
    AutoSmeltEnchantmentEffect.initialize();
        LOGGER.info("自动熔炼附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("magnet")) {
    MagnetEnchantmentEffect.initialize();
        LOGGER.info("磁力附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("step")) {
    StepEnchantmentEffect.initialize();
        LOGGER.info("自动台阶附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("reach")) {
    ReachEnchantmentEffect.initialize();
        LOGGER.info("延伸打击附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("life_leech")) {
    LifeLeechEnchantmentEffect.initialize();
        LOGGER.info("生命汲取附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("beheading")) {
    BeheadingEnchantmentEffect.initialize();
        LOGGER.info("斩首附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("experience_boost")) {
    ExperienceBoostEnchantmentEffect.initialize();
        LOGGER.info("经验提升附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("growth")) {
    GrowthEnchantmentEffect.initialize();
        LOGGER.info("成长附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("beekeeper")) {
    BeekeeperEnchantmentEffect.initialize();
        LOGGER.info("养蜂人附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("multibow")) {
    MultiBowEnchantmentEffect.initialize();
        LOGGER.info("多重射击附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("quickdraw")) {
    QuickdrawEnchantmentEffect.initialize();
        LOGGER.info("快速拉弦附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("multijump")) {
    MultiJumpEnchantmentEffect.initialize();
        LOGGER.info("多重跳跃附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("traveller")) {
    TravellerEnchantmentEffect.initialize();
        LOGGER.info("旅行者附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("laststand")) {
    LastStandEnchantmentEffect.initialize();
        LOGGER.info("最后一击附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("gloom_curse")) {
    GloomCurseEnchantmentEffect.initialize();
        LOGGER.info("阴暗诅咒附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("ender_pearl")) {
    EnderPearlEnchantmentEffect.initialize();
        LOGGER.info("末影珍珠附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("steady")) {
    SteadyEnchantmentEffect.initialize();
        LOGGER.info("稳定附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("block_reach")) {
    BlockReachEnchantmentEffect.initialize();
        LOGGER.info("方块范围扩展附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("venom")) {
    VenomEnchantmentEffect.init();
        LOGGER.info("毒液附魔已启用");
    }
    if (EnchantRegistry.isEnchantEnabled("sword_aura")) {
        SwordAuraEnchantmentEffect.initialize();
        LOGGER.info("御剑术附魔已启用");
    }
    
    int enabledCount = getEnabledEnchantCount();
    int totalCount = ALL_ENCHANT_NAMES.size();
    
    LOGGER.info("路西法的宝藏 模组初始化完成！");
    LOGGER.info("已启用 {} / {} 个附魔效果", enabledCount, totalCount);
    
    if (enabledCount < totalCount) {
        LOGGER.info("有 {} 个附魔被禁用。可在配置文件中修改: lucifer-treasure-enchants.properties", totalCount - enabledCount);
    }
    
    // 🚀 优化：高频率智能更新御剑术状态
    net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents.END_SERVER_TICK.register(server -> {
        // 每tick检查所有玩家的御剑术 - 消除闪烁，提供流畅的视觉效果
            for (net.minecraft.server.network.ServerPlayerEntity player : server.getPlayerManager().getPlayerList()) {
                com.lucifer.treasure.enchant.effect.SwordAuraEnchantmentEffect.handleSwordAuraEffect(player);
        }
    });
  }

  public static void log(String string) {
    LOGGER.info(string);
  }
  
  /**
   * 打印附魔配置状态
   */
  private void printEnchantConfigStatus() {
    LOGGER.info("=== 附魔配置状态 ===");
    
    Map<String, Boolean> statusMap = ConfigHandler.getAllEnchantEnabledStatus();
    
    for (String enchantName : ALL_ENCHANT_NAMES) {
        boolean enabled = statusMap.getOrDefault(enchantName, true);
        String status = enabled ? "启用" : "禁用";
        String displayName = getDisplayName(enchantName);
        
        LOGGER.info("[{}] {} - {}", status, enchantName, displayName);
    }
    
    LOGGER.info("===================");
  }
  
  /**
   * 获取附魔的显示名称（中文）
   */
  private String getDisplayName(String enchantName) {
    return switch (enchantName) {
        case "auto_smelt" -> "自动熔炼";
        case "step" -> "自动台阶";
        case "steady" -> "稳定";
        case "experience_boost" -> "经验提升";
        case "traveller" -> "旅行者";
        case "magnet" -> "磁力";
        case "excavation" -> "连锁挖掘";
        case "reach" -> "延伸打击";
        case "venom" -> "毒液";
        case "beheading" -> "斩首";
        case "disarm" -> "缴械";
        case "growth" -> "成长";
        case "life_leech" -> "生命汲取";
        case "beekeeper" -> "养蜂人";
        case "block_reach" -> "方块范围扩展";
        case "multibow" -> "多重射击";
        case "quickdraw" -> "快速拉弦";
        case "multijump" -> "多重跳跃";
        case "laststand" -> "最后一击";
        case "gloom_curse" -> "阴暗诅咒";
        case "ender_pearl" -> "末影珍珠";
        case "sword_aura" -> "御剑术";
        default -> enchantName;
    };
  }
  
  /**
   * 获取启用的附魔数量
   */
  private int getEnabledEnchantCount() {
    int count = 0;
    for (String enchantName : ALL_ENCHANT_NAMES) {
        if (EnchantRegistry.isEnchantEnabled(enchantName)) {
            count++;
        }
    }
    return count;
  }
}
